package cn.stylefeng.guns.utils.douyin;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class Decrypt {
    public static String decrypt(String encryptedData, String sessionKey, String iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] sessionKeyBytes = decoder.decode(sessionKey);
        byte[] ivBytes = decoder.decode(iv);
        byte[] encryptedBytes = decoder.decode(encryptedData);

        // JDK does not support PKCS7Padding, use PKCS5Padding instead
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        byte[] ret = cipher.doFinal(encryptedBytes);
        return new String(ret);
    }

    public static void main2(String []args)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

        String encryptedData="g5VHtK6P7zNJPoKZMjrzigXRNzBIZHTVnmUjBkhFiNTfAF+VYgCpgfohpI0NzQufmzEvrfkHHU58iJVK+k35q4Z8bWl2SA8yss6vM95i2Y7BmsUudTBmzp8s5hl6wsHoy6COqQXhfso7xaO3ub/JUN3c0OdhsZVyex4uy0RTLtcS0e2c+x5yBItAUAHk/fVPZvTXs2y3J7zlvC5tJ97DXw==";
        String sessionKey="/CI9DwoR7q4y0tD4O0jeyQ==";
        String iv="YLAaJ7hPHF5SrO0FMJtchw==";
        String mobile = decrypt(encryptedData, sessionKey, iv);
        System.out.println(mobile);
    }
}